﻿using UnityEngine;
using System.Collections;

using System.Collections.Generic;
using UnityEditor;

public class scGameManager : MonoBehaviour {

	public Sprite [] resultSprite = new Sprite[2];


	public enum GameStatus
	{
		Playing = 0,
		Completed,
		Failed,
		Pause,

		Count
	}

	enum BirdPath
	{
		Begin = 0,
		Mid,
		End,
		
		Count
	}


	private static GameStatus gameStatus = GameStatus.Playing;

	private static GameObject toolboxIngame;
	private static GameObject resultboxIngame;

	
	private Vector4 catapultReadyPoint;
	private SortedList birds = new SortedList();
	private int leftBirds = 0;
	private int leftPigs = 0;

	private GameObject [] birdPathImages = new GameObject[(int)BirdPath.Count];
	private Transform flyingBird = null;
	private float printingPathTime = 0f;
	private BirdPath birdPathIndex = BirdPath.Begin;
	private List<GameObject> birdPathList = new List<GameObject>();
	private int birdPathLastPos = 0;
	private float printPathSkipFrame = 0;

	private static int totalScore = 0;
	private static int highScore = 0;
	private static GUIText guiScore;
	private static GUIText guiHighScore;
	private static int level;


	public static void GamePause()
	{
		gameStatus = GameStatus.Pause;

		scFadeEffectManager.SetScreenPause(true);

		iTween.MoveTo(toolboxIngame, iTween.Hash("x", -7.9f, "y", 0f, "easeType", iTween.EaseType.linear));
	}

	public static void GameResume()
	{
		gameStatus = GameStatus.Playing;

		scFadeEffectManager.SetScreenPause(false);

		iTween.MoveTo(toolboxIngame, iTween.Hash("x", -10.9f, "y", 0f, "easeType", iTween.EaseType.linear));
	}

	public static void GameRestart()
	{
		gameStatus = GameStatus.Playing;

		scFadeEffectManager.SetScreenPause(false);

		Application.LoadLevel(Application.loadedLevel);
	}

	public static void GotoStage()
	{
		Application.LoadLevel(1);
	}

	public static void NextLevel()
	{
		int nextLevel = level + 1;
		Application.LoadLevel("level_" + nextLevel);
	}

	public static GameStatus GetCurrentGameStatus()
	{
		return gameStatus;
	}

	public static void AddScore(int score)
	{
		totalScore += score;

		guiScore.text = totalScore.ToString();

		if (totalScore > highScore)
		{
			highScore = totalScore;
			guiHighScore.text = highScore.ToString();
			scPlayerInfo.SetHighScore(level, highScore);
		}
	}

	// this for initialization
	void Start () {
		gameStatus = GameStatus.Playing;
		level = int.Parse(Application.loadedLevelName.Remove(0, 6));

		Debug.Log ("start new game status =" + gameStatus);
		Debug.Log ("game level =" + level);
		scFadeEffectManager.SetScreenPause(false);

		_InitGameObjects();
		_InitScoreBoard();

		Invoke("_SetNextBird", 2);
	}
	
	// Update is called once per frame
	void Update () {
	}
	
	void FixedUpdate()
	{
		_PrintBirdPath();
	}
		
	void BeginBirdPath(Transform bird)
	{
		flyingBird = bird;
		printingPathTime = 1;
		birdPathLastPos = birdPathList.Count;
	}
	
	void StopBirdPath()
	{
		flyingBird = null;
		birdPathIndex = BirdPath.Begin;
		
		for (int n = 0 ; n < birdPathLastPos ; ++n)
		{
			GameObject gb = birdPathList[n];
			DestroyObject(gb);
		}
		birdPathList.RemoveRange(0, birdPathLastPos);
	}
	
	void SetNextBird()
	{
		Invoke("_SetNextBird", 2);
	}

	void DiedBird()
	{
		--leftBirds;

		_IsFinishedLevel();
	}

	void DiedPig()
	{
		--leftPigs;

		_IsFinishedLevel();
	}

	void _SetNextBird()
	{
		if (birds.Count == 0)
		{
			// wait for game over
			return;
		}
		
		GameObject readyBird = (GameObject)birds.GetByIndex(0);
		readyBird.SendMessage("SetReady", catapultReadyPoint, SendMessageOptions.DontRequireReceiver);

		birds.RemoveAt(0);
	}

	void _InitGameObjects()
	{
		toolboxIngame = GameObject.Find("pfToolboxIngame");
		resultboxIngame = GameObject.Find("pfResultboxIngame");
		resultboxIngame.transform.position = new Vector3(-1000, -1000, -1000);

		GameObject catapult = GameObject.Find("CatapultReadyPosition");
		if (catapult == null)
		{
			return;
		}
		
		CircleCollider2D cc2d = catapult.GetComponent<CircleCollider2D>();
		if (cc2d == null)
		{
			return;
		}
		catapultReadyPoint = cc2d.transform.position;
		catapultReadyPoint.w = cc2d.radius;


		GameObject [] allBirds = GameObject.FindGameObjectsWithTag("Bird");
		foreach(GameObject bird in allBirds)
		{
			if(bird.transform.position.x != 0 || bird.transform.position.y != 0)
			{
				birds.Add(bird.transform.position.x, bird);
			}
		}
		leftBirds = birds.Count;
		
		GameObject [] allPigs = GameObject.FindGameObjectsWithTag("Pig");
		leftPigs = allPigs.Length;

		// bird path image init
		birdPathImages[(int)BirdPath.Begin] = (GameObject)Instantiate(
			Resources.Load("Prefabs/Birds/pfBirdPathBegin"),
			new Vector3(0f, 0f, -10f),
			Quaternion.Euler(0f, 0f, 0f)
			);

		birdPathImages[(int)BirdPath.Mid] = (GameObject)Instantiate(
			Resources.Load("Prefabs/Birds/pfBirdPathMid"),
			new Vector3(0f, 0f, -10f),
			Quaternion.Euler(0f, 0f, 0f)
			);

		birdPathImages[(int)BirdPath.End] = (GameObject)Instantiate(
			Resources.Load("Prefabs/Birds/pfBirdPathEnd"),
			new Vector3(0f, 0f, -10f),
			Quaternion.Euler(0f, 0f, 0f)
			);
	}

	void _InitScoreBoard()
	{
		highScore = scPlayerInfo.GetHighScore(level);

		Vector3 scoreViewPos = new Vector3();
		scoreViewPos.x = 0.99f;
		scoreViewPos.z = 0f;
	
		GameObject scoreBoard = (GameObject)Instantiate(
			Resources.Load("Prefabs/pfScoreBoard"),
			new Vector3(0f, 0f, 0f),
			Quaternion.Euler(0f, 0f, 0f)
			);

		GUIText [] scores = scoreBoard.GetComponentsInChildren<GUIText>();
		foreach(GUIText guiText in scores)
		{
			if (guiText.name == "ScoreTitle")
			{
				scoreViewPos.y = 0.99f;
				guiText.transform.position = scoreViewPos;
			}
			else if (guiText.name == "Score")
			{
				scoreViewPos.y = 0.93f;
				guiText.transform.position = scoreViewPos;
				guiScore = guiText;
			}
			else if (guiText.name == "HighScoreTitle")
			{
				scoreViewPos.y = 0.85f;
				guiText.transform.position = scoreViewPos;
			}
			else if (guiText.name == "HighScore")
			{
				scoreViewPos.y = 0.80f;
				guiText.transform.position = scoreViewPos;
				guiHighScore = guiText;
				guiHighScore.text = highScore.ToString();
			}
		}
	}

	void _PrintBirdPath()
	{
		if (flyingBird == null)
		{
			return;
		}
		
		if (printPathSkipFrame == 0)
//		if (printingPathTime >= 0.03f)
		{
			++printPathSkipFrame;
			printingPathTime = 0f;
			
			GameObject newBirdPath = (GameObject)Instantiate (birdPathImages[(int)birdPathIndex], flyingBird.position, flyingBird.rotation);
			birdPathList.Add (newBirdPath);
			
			if (birdPathIndex == BirdPath.Begin)
			{
				birdPathIndex = BirdPath.Mid;
			}
			else if (birdPathIndex == BirdPath.Mid)
			{
				birdPathIndex = BirdPath.End;
			}
			else if (birdPathIndex == BirdPath.End)
			{
				birdPathIndex = BirdPath.Begin;
			}
		}
		else
		{			
			if (++printPathSkipFrame == 3)
			{
				printPathSkipFrame = 0;
			}
			printingPathTime += Time.deltaTime;
		}
	}

	void _IsFinishedLevel()
	{
		if (gameStatus != GameStatus.Playing)
		{
			return;
		}

		if (leftPigs == 0)
		{
			gameStatus = GameStatus.Completed;

			Invoke("_ResultOfLevel", 5f);
		}
		else if (leftBirds == 0)
		{
			gameStatus = GameStatus.Failed;

			Invoke("_ResultOfLevel", 5f);
		}
	}

	void _ResultOfLevel()
	{
		scFadeEffectManager.SetScreenPause(true);

		resultboxIngame.transform.position = new Vector3(0, 0, 0);

		GUIText guiText = resultboxIngame.GetComponentInChildren<GUIText>();
		guiText.transform.position = new Vector3(0.5f, 0.7f, 0f);;

		SpriteRenderer [] childSpriteRender = resultboxIngame.GetComponentsInChildren<SpriteRenderer>();
		foreach (SpriteRenderer spriteRender in childSpriteRender)
		{
			if (spriteRender.name == "ResultImage")
			{
				if (gameStatus == GameStatus.Completed)
				{
					spriteRender.sprite = resultSprite[0];
					guiText.text = "LEVEL CLEARED!";
				}
				else
				{
					spriteRender.sprite = resultSprite[1];
					guiText.text = "LEVEL FAILED!";

					foreach(SpriteRenderer obj in childSpriteRender)
					{
						if (obj.name == "pfButtonNextLevel")
						{
							obj.renderer.enabled = false;
							return;
						}
					}
				}

				return;
			}
		}
	}
}
